﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using CrawlerCore;
using WCrawlerLib;

namespace WCrawler.Controls
{
    public partial class ucForumThreadPosts : System.Web.UI.UserControl
    {
        /// <summary>
        /// Biến dùng cho thể hiện số thứ tự của một forum
        /// </summary>
        //private int _indexForumThread = 0;

        private int _indexThreadPost = 0;

        //private Forum _forum;
        /// <summary>
        /// .//table[@id='threadslist']/tbody/tr
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //Panel pnlCommand = (Panel)ucForumControl.FindControl("pnlCommand");
                //pnlCommand.Visible = false;
                //GridView gridViewForums = (GridView)ucForumControl.FindControl("gridViewForums");
                //gridViewForums.SelectedIndex = 0;
                //CommandField cmdField = (CommandField)gridViewForums.Columns[0];
                //cmdField.ShowEditButton = false;
                //cmdField.ShowDeleteButton = false;
            }
        }

        public Forum GetForumSession(int forumId)
        {
            Forum forum;
            //Get obj _forum
            if (Session[forumId.ToString()] != null)
            {
                forum = (Forum)Session[forumId.ToString()];
            }
            else
            {
                forum = new Forum();
                forum = forum.GetForum(forumId);
                Session[forumId.ToString()] = forum;
            }
            return forum;
        }

        public void Search(bool isUsePaging, bool isSearchLatestThread)
        {
            try
            {
                GridView gridViewForums = (GridView)Session["ucForum_GridViewForums"];
                if (gridViewForums == null)
                    return;

                Parallel.ForEach<GridViewRow>(gridViewForums.Rows.OfType<GridViewRow>(), di =>
                {
                    CheckBox chkBx = (CheckBox)di.FindControl("chkCheckItem");
                    if (chkBx != null && chkBx.Checked)
                    {
                        Forum objForum = GetForumSession((int)gridViewForums.DataKeys[di.RowIndex].Value);
                        objForum.LoadForum();
                        if (objForum.LoginStatus)
                        {
                            //Get search template
                            ForumTemplateDetail obj = new ForumTemplateDetail();
                            string statisticUrl = obj.GetStatisticUrl(objForum.ForumId, objForum.ForumTypeId);
                            DataTable myTable = WGeneralClass.CreateSearchForumThreadDataTable();
                            
                            //Fill userid into search template
                            statisticUrl = statisticUrl.Replace("[userid]", objForum.UserId.Value.ToString());
                            //Search and return result into a table
                            myTable = objForum.Browser.SearchForumThreads(objForum.ForumUrl, statisticUrl, "", myTable, isUsePaging, isSearchLatestThread);
                            foreach (DataRow dr in myTable.Rows)
                            {
                                PostDetail objPostDetail = new PostDetail();
                                objPostDetail = objPostDetail.GetPostDetailByTitle(objForum.LanguageId.Value, dr["Title"].ToString());
                                if (objPostDetail != null)
                                {
                                    dr["PostId"] = objPostDetail.Post.PostId;
                                }
                            }
                            
                            Session["myTable" + objForum.ForumId] = myTable;
                        }
                    }
                });

                //Binding search result for selected forum
                SearchForumThreadDataBind();

                //Auto update when searching finish
                UpdateForumThreadInfo();
            }
            catch (AggregateException aggEx)
            {
                foreach (Exception ex in aggEx.InnerExceptions)
                {
                    Response.Write("Caught exception" + ex.Message);
                }
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Search(true, false);
        }

        public void SearchForumThreadDataBind()
        {
            if (Session["ucForum_SelectedValue"] != null)
            {
                string key = "myTable" + Session["ucForum_SelectedValue"].ToString();
                DataTable _myTable = WGeneralClass.CreateSearchForumThreadDataTable();
                if (Session[key] != null)
                    _myTable = (DataTable)Session[key];
                gridViewSeachForumThread.DataSource = _myTable;
                gridViewSeachForumThread.DataBind();
                gridViewSeachForumThread.AllowSorting = true;

                //Update threadpost after search
                gridViewThreadPosts.DataBind();
            }
        }

        protected void ForumThreadsLinqDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            if (Session["ucForum_SelectedValue"] != null)
            {
                ForumThread objForumThread = new ForumThread();
                e.Result = objForumThread.GetForumThreadByForum((int)Session["ucForum_SelectedValue"]);
            }
        }

        public void UpdateForumThreadPost(GridViewRow row)
        {
            //================================================================================================
            //Get forum 
            Forum forum = GetForumSession((int)Session["ucForum_SelectedValue"]);

            //================================================================================================
            //Get values in controls
            HyperLink hyperLinkThread = (HyperLink)row.FindControl("hyperLinkThread");
            DropDownList dropDownListPost = (DropDownList)row.FindControl("PostDropDownList");
            if (dropDownListPost.SelectedIndex == -1)
                return;

            int postId = int.Parse(dropDownListPost.SelectedValue);
            //Get PostDetaislId
            PostDetail objPostDetail = new PostDetail();
            objPostDetail = objPostDetail.GetExactlyPostDetail(postId, forum.LanguageId);

            int threadNum = int.Parse(((Label)row.FindControl("lblThreadNum")).Text);
            int postNum = int.Parse(((Label)row.FindControl("lblPostNum")).Text);
            int replies = int.Parse(((Label)row.FindControl("lblReplies")).Text);
            int views = int.Parse(((Label)row.FindControl("lblViews")).Text);

            ForumThread objForumThread = new ForumThread
            {
                ForumId = forum.ForumId,
                ThreadNum = threadNum,
                ThreadTitle = objPostDetail.PostTitle,
                ThreadUrl = hyperLinkThread.NavigateUrl.Replace(forum.ForumUrl + "/", ""),
                Replies = replies,
                Views = views
            };

            ThreadPost objThreadPost = new ThreadPost();
            objThreadPost = objThreadPost.GetThreadPost(objForumThread.ForumThreadId, objPostDetail.PostDetailsId);
            if (objThreadPost != null)
                objThreadPost.UpdateThreadPost(objPostDetail.PostDetailsId, postNum);
            else
            {
                objThreadPost = new ThreadPost
                {
                    PostDetailsId = objPostDetail.PostDetailsId,
                    PostNum = postNum,
                    IsFirstPost = true,
                };

                objForumThread.ThreadPosts.Add(objThreadPost);
            }

            objForumThread.UpdateForumThread(postId, forum.ForumId, objForumThread);
            
        }

        /// <summary>
        /// Update Info of forum threads after search complete
        /// </summary>
        protected void UpdateForumThreadInfo()
        {
            //Update thread num, post num
            foreach (GridViewRow threadPostRow in gridViewThreadPosts.Rows)
            {
                Label lblThreadNum = (Label)threadPostRow.FindControl("lblThreadNum");
                int threadNum = int.Parse(lblThreadNum.Text);
                //Update postforumdetail by threadNum
                int rowIndex = gridViewSeachForumThread.DataKeys.IndexOf("ThreadNum", threadNum.ToString());
                if (rowIndex != -1)
                {
                    GridViewRow row = gridViewSeachForumThread.Rows[rowIndex];
                    UpdateForumThreadPost(row);
                }
            }
            gridViewThreadPosts.DataBind();
        }

        protected void btnAddThreads_Click(object sender, EventArgs e)
        {
            Forum forum = GetForumSession((int)Session["ucForum_SelectedValue"]);
            Parallel.ForEach<GridViewRow>(gridViewSeachForumThread.Rows.OfType<GridViewRow>(), row =>
            {
                CheckBox chkBx = (CheckBox)row.FindControl("chkItemSearchForumThread");
                if (chkBx != null && chkBx.Checked)
                {
                    UpdateForumThreadPost(row);
                }
            });
            SearchForumThreadDataBind();
        }

        protected void gridViewSeachForumThread_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label lblId = (Label)e.Row.FindControl("lblThreadNum");
                if (lblId.Text != string.Empty)
                {
                    ForumThread objForumThread = new ForumThread();
                    if (!objForumThread.IsThreadNumExists((int)Session["ucForum_SelectedValue"], int.Parse(lblId.Text)))
                    {
                        e.Row.BackColor = System.Drawing.Color.Yellow;
                        e.Row.ForeColor = System.Drawing.Color.Red;
                    }
                }
            }
        }

        //protected void gridViewForumThreads_RowDataBound(object sender, GridViewRowEventArgs e)
        //{
        //    if (e.Row.RowType == DataControlRowType.Header)
        //        _indexForumThread = gridViewForumThreads.PageSize * gridViewForumThreads.PageIndex + 1;
        //    else if (e.Row.RowType == DataControlRowType.DataRow)
        //    {
        //        //Create order numbers
        //        ((Label)e.Row.FindControl("lblNum")).Text = (_indexForumThread++).ToString();
        //    }
        //    //if (e.Row.RowType == DataControlRowType.DataRow)
        //    //{
        //    //    ForumThread objForumThread = new ForumThread();
        //    //    objForumThread = objForumThread.GetForumThreads((int)gridViewForumThreads.DataKeys[e.Row.RowIndex]["ForumThreadId"]);
        //    //    HyperLink hyperLinkThread = (HyperLink)e.Row.FindControl("hyperLinkThread");
        //    //    hyperLinkThread.NavigateUrl = objForumThread.Forum.ForumUrl + "/" + objForumThread.ThreadUrl;
        //    //    hyperLinkThread.Text = objForumThread.ThreadTitle;
        //    //}
        //}

        protected void ThreadPostLinqDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            int id = -1;
            if (Session["ucForum_SelectedValue"] != null)
            {
                id = (int)Session["ucForum_SelectedValue"];
            }

            ThreadPost objThreadPost = new ThreadPost();
            e.Result = objThreadPost.GetAll().WhereForum(id.ToString());
        }

        protected void btnUpdatePostNum_Click(object sender, EventArgs e)
        {
            Forum objForum = GetForumSession((int)Session["ucForum_SelectedValue"]);
            objForum.LoadForum();
            Parallel.ForEach<GridViewRow>(gridViewThreadPosts.Rows.OfType<GridViewRow>(), row =>
            {
                CheckBox chkBx = (CheckBox)row.FindControl("chkItemThreadPost");
                if (chkBx != null && chkBx.Checked)
                {
                    HyperLink hyperLinkThread = (HyperLink)row.FindControl("hyperLinkThread");
                    string[] result = new string[2];
                    result = objForum.Browser.GetThreadPostNum(hyperLinkThread.NavigateUrl);
                    
                    ForumThread objForumThread = new ForumThread();
                    objForumThread.UpdateThreadNum((int)gridViewThreadPosts.DataKeys[row.RowIndex]["ForumThreadId"], int.Parse(result[0]));

                    ThreadPost objThreadPost = new ThreadPost();
                    objThreadPost.UpdatePostNum((int)gridViewThreadPosts.DataKeys[row.RowIndex]["ForumThreadId"],(int)gridViewThreadPosts.DataKeys[row.RowIndex]["PostDetailsId"], int.Parse(result[1]));
                }
            });
            gridViewThreadPosts.DataBind();
        }

        protected void gridViewThreadPosts_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
                _indexThreadPost = gridViewThreadPosts.PageSize * gridViewThreadPosts.PageIndex + 1;
            else if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //Create order numbers
                ((Label)e.Row.FindControl("lblNum")).Text = (_indexThreadPost++).ToString();
            }
        }

        protected void btnCheckThreads_Click(object sender, EventArgs e)
        {

        }

        protected void btnSearchLatestThread_Click(object sender, EventArgs e)
        {
            Search(false, true);
        }

        protected void btnDeleteThreads_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in gridViewThreadPosts.Rows)
            {
                CheckBox chk = (CheckBox)row.FindControl("chkItemThreadPost");
                if (chk.Checked)
                {
                    ForumThread objForumThread = new ForumThread();
                    objForumThread.DeleteForumThread((int)gridViewThreadPosts.DataKeys[row.RowIndex]["ForumThreadId"]);
                }
            }
            gridViewThreadPosts.DataBind();
        }

        protected void btnUpdateTemplate_Click(object sender, EventArgs e)
        {

        }
    }
}